using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MiniProfiler.Api.Models;

namespace MiniProfiler.Api.Controllers;

[ApiController]
[Route("[controller]")]
public class OrderController : ControllerBase
{
    private readonly ILogger<OrderController> _logger;
    private readonly AppDbContext _dbContext;

    public OrderController(ILogger<OrderController> logger, AppDbContext dbContext)
    {
        _logger = logger;
        _dbContext = dbContext;
    }

    [HttpGet]
    public IEnumerable<Order> GetList()
    {
        _logger.LogInformation("Start");
        var orders = _dbContext.Orders.AsEnumerable();
        _logger.LogInformation("End");

        return orders;
    }

    [HttpGet("{id}")]
    public async Task<Order?> Get(int id)
    {
        _logger.LogInformation("Start");
        var order = await _dbContext.Orders.Where(o => o.Id == id).FirstOrDefaultAsync();
        _logger.LogInformation("End");

        return order;
    }

    [HttpPost]
    public async Task<Order> Create()
    {
        _logger.LogInformation("Start");
        var order = await _dbContext.Orders.AddAsync(new Order()
        {
            Name = DateTime.Now.ToString(),
        });
        await _dbContext.SaveChangesAsync();
        _logger.LogInformation("End");

        return order.Entity;
    }
}
